package com.xcj.cloud.utils;


import com.xcj.cloud.entity.House;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Component
@PropertySource("classpath:application.yml")
public class FileAction {

    @Value("${upload-path}")
    public String path;

    /**
     * 上传宣传图
     *
     * @param house
     * @param fileImg
     * @return
     */
    public House publicityImg(House house, MultipartFile fileImg) throws IOException {
        String filename = getFilename(fileImg);
        //保存文件
        write(fileImg.getBytes(), path + filename);
        return house.setImg(filename);
    }

    /**
     * 上传详情图
     *
     * @param house
     * @param fileArr
     * @return
     * @throws IOException
     */
    public House detailsImg(House house, MultipartFile[] fileArr) throws IOException {
        //循环获取图片详情的名称，以逗号间隔
        StringBuffer imagesName = new StringBuffer();
        for (int i = 0; i < fileArr.length; i++) {
            MultipartFile file = fileArr[i];
            String filename = getFilename(file);
            write(file.getBytes(), path + filename);
            imagesName.append(filename);
            if (i != fileArr.length - 1) {
                imagesName.append(",");
            }
        }
        return house.setImages(imagesName.toString());
    }

    /**
     * 获取唯一不重复的文件名
     *
     * @param file
     * @return
     */
    public String getFilename(MultipartFile file) {
        String filename = file.getOriginalFilename(); //获取文件名
        String suffix = filename.substring(filename.lastIndexOf("."));  //获取后缀名
        String onlyID = UUID.randomUUID().toString()
                .replace("-", "");
        filename = onlyID + suffix;
        return filename;
    }

    /**
     * 写入到磁盘中
     *
     * @param data
     * @param file
     * @throws IOException
     */
    public void write(byte[] data, String file) throws IOException {
        //使用缓冲流提高读写性能
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(data);
        bos.close();
    }

    /**
     * 删除本地文件
     *
     * @param filename
     */
    public void delFile(String filename) {
        File file = new File(path + filename);
        file.delete();
    }

    /**
     * 上传宣传图和详情图
     *
     * @param house
     * @param fileImg
     * @param fileArr
     * @return
     * @throws IOException
     */
    public House uploadImage(House house, MultipartFile fileImg,
                             MultipartFile[] fileArr) throws IOException {

        return detailsImg(publicityImg(house, fileImg), fileArr);

    }
}
